export function dictionaryReducer(state: any, action: any) {
    if (action.name !== 'dictionary') return state;
  switch (action.type) {
    case 'catchError': {
      return {
        ...state,
        error: action.payload.error,
        loading: false,
      };
    }
    case 'start': {
      return {
        ...state,
        error: null,
        loading: true,
      };
    }
    case 'end': {
      return {
        ...state,
        loading: false,
      };
    }
    case 'entitiesFetched': {
      const { totalCount, entities, offset } = action.payload;
      console.log(" totalCount, entities, offset", totalCount, entities, offset)
      return {
        ...state,
        entities,
        totalCount,
        offset,
        error: null,
        loading: false,
      };
    }
    case 'entityCreated': {
      return {
        ...state,
        entities: [...state.entities, action.payload.entity],
        totalCount: state.totalCount + 1,
        error: null,
        loading: false,
      };
    }
    case 'entitySet': {
        const { index, entity} = action.payload;
        return {
          ...state,
          index,
          entity,
          error: null,
        };
      }
      case 'entityDeleted': {
        return {
          ...state,
          entity:{},
          index:-1,
          entities: state.entities.filter(
            (el:any) => el[state.key] !== action.payload.key
          ),
          error: null,
          loading: false,
        };
      }
      case 'entityUpdated': {
        return {
          ...state,
          entity:action.payload.entity,
          entities: state.entities.map((entity:any) =>
          entity[state.key] === action.payload.entity[state.key]
            ? action.payload.entity
            : entity
        ),
          error: null,
          loading: false,
        };
      }
    default: {
      return state;
      // throw Error('Unknown action: ' + action.type);
    }
  }
}

export const initialDictionary = {
  loading: false,
  entities: [],
  totalCount: 0,
  entity: {},
  // 当前 entiy 在 entities 中的 index
  index: -1,
  // 当前 entities 在 total 中的 offset
  offset: 0,
  error: null,
  key: 'id',
};
